總共三步:在urls中加入一個path,在views中加入一個function,在template的html中進行post or get;
首先我們來看第一步:
在urls中加一個path,為了方便使用,我們加一個帶了option的path,這樣就可以一個path做多個事情;
代碼:
path('link_db/<str:option>/<str:shedId>/<str:oldPathName>/<str:newPathName>/<str:note>', views.updatePathName, name='updatePathName'),
這裡的第一個參數option,就是用來作為選項的;
第二步,在views中實現這個function;
代碼:
def updatePathName(request,option,shedId,oldPathName,newPathName,note):
### update pathname
print('updatePathName',option)
if option == 'updatePathName':
if dbManager.updatePathName(shedId,oldPathName,newPathName):
return JsonResponse({'result':'success','oldpathname': oldPathName,'newpathname':newPathName})
return JsonResponse({'result':'fail','oldpathname': oldPathName,'newpathname':newPathName})
return JsonResponse({'result':'fail'})
把option作為判斷條件;
第三步:在html中進行請求:
代碼:
function reqListener() {
console.log(this.responseText);
var response = JSON.parse(this.responseText);
// console.log(response);
var tmp_res = decodeURI(response['result']);
console.log(tmp_res);
}
//todo send requests
var oReq = new XMLHttpRequest();
oReq.addEventListener("load", reqListener);
oReq.open("GET", 'updatePathName' + '/' + shedId + '/' + oldPathName + '/' + newPathName + '/' + 'pengzhen');
oReq.send();
另外,如果要使用post的話,這樣調用:
var oReq = new XMLHttpRequest();
oReq.addEventListener("load", reqListener);
// oReq.open("GET", 'decodePathLine_toPolygon' + '/' + pathname + '/' + str_paths);
oReq.open("post", 'decodePathLine_toPolygon' + '/' + pathname + '/' + pathname);
// const csrftoken = document.querySelector('[name=csrfmiddlewaretoken]').value
oReq.setRequestHeader("X-CSRFToken", '{{ csrf_token|safe }}');
// oReq.setRequestHeader("Content-Type", "text/plain;charset=UTF-8");
oReq.send(str_paths);